<template>
  <div class="login">
    <div class="login-wrap">
      <div class="login-title">
        <div>
          <el-avatar class="img"> LOGO </el-avatar>
        </div>
        <h2 class="title-text">XXX系统</h2>
        <h2 class="title-desc">XXX系统的描述文案</h2>
      </div>

      <div class="login-container">
        <div class="login-internal">
          <!-- 选项卡 -->
          <div class="login-tabs">
            <div class="tabs-animate tabs-item tabs-active">账户密码登录</div>
            <div class="tabs-animate tabs-border"></div>
          </div>

          <!-- 用户登录表单部分 -->
          <el-form
            class="login-form admin-form"
            ref="adminRuleForm"
            label-width="0px"
            label-position="left"
            :model="adminInfo"
            :rules="adminRules"
          >
            <!-- 管理账号 -->
            <el-form-item prop="adminAccount">
              <el-input
                type="text"
                v-model="adminInfo.adminAccount"
                placeholder="请输入账号"
                clearable
              >
                <div slot="prefix" class="login-icon login-icon-manage"></div>
              </el-input>
            </el-form-item>
            <!-- 密码 -->
            <el-form-item prop="password">
              <!-- type="password" -->
              <el-input
                style="margin-top: 10px"
                v-model="adminInfo.password"
                placeholder="请输入6-16位密码，区分大小写"
                clearable
                show-password
              >
                <div slot="prefix" class="login-icon login-icon-password"></div>
              </el-input>
            </el-form-item>
            <el-checkbox class="remember" v-model="remember"
              >记住密码</el-checkbox
            >
            <el-form-item style="width: 100%">
              <el-button
                type="primary"
                class="login-btn"
                :loading="logining"
                @click="onUserLogin()"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// vuex中的state数据
import { mapState, mapGetters } from "vuex";

// 工具类
import md5 from "js-md5";
import { getStore, setStore } from "@/utils/util";
import { TABSINDEX, VOICEAVATARFILE } from "@/utils/const";

export default {
  name: "Login",

  // 组件数据存储
  data() {
    return {
      // 登录状态
      logining: false,
      // 记住密码: 默认勾选
      remember: true,
      // 管理用户 「登录信息对象」
      adminInfo: {
        adminAccount: "",
        password: "",
      },
      // 「前端验证非空」
      adminRules: {
        adminAccount: [
          { required: true, message: "请输入管理账号", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },

  // 计算属性
  computed: {
    // vuex中的 state数据
    ...mapState({
      vRole: (state) => state.role,
      vName: (state) => state.adminAccount,
      vPassword: (state) => state.password,
      vRemember: (state) => state.remember,
    }),
    ...mapGetters(["jumpRouterName"]),
  },

  // 创建完毕状态(里面是操作)
  created() {
    // TODO: 注册管理账号接口 暂时不对外开放
    // this.TheRegister("奇梦者测试5", "123456");
    // 根据本地缓存中保存的记住密码状态来判断是否需要给用户看账户和密码
    if (this.vRemember) {
      this.adminInfo.adminAccount = this.vName;
      this.adminInfo.password = this.vPassword;
      this.remember = this.vRemember;
    } else {
      this.adminInfo.adminAccount = "";
      this.adminInfo.password = "";
    }
  },

  // 创建与销毁监听回车事件
  mounted() {
    // TODO: 这里的延时是我为了解决退出弹出直接使用回车与此添加的回车事件冲突而写
    // 产品需求 不需要回车事件绑定
    // setTimeout(() => {
    //   window.addEventListener("keyup", this.EnterConfirm);
    // }, 800);
  },
  destroyed() {
    // window.removeEventListener("keyup", this.EnterConfirm);
  },

  // 里面的函数只有调用才会执行
  methods: {
    // ======================= 后端API =======================
    // 「注册」
    TheRegister(account, password) {
      this.$api
        .register(account, password, password)
        .then((res) => {
          if (res.code == 0) {
            console.log("注册成功 =>", res);
          } else {
            console.log("失败信息 =>", res);
          }
        })
        .catch((err) => {
          console.log("注册失败 =>", err);
        });
    },

    // 「登录」
    TheLogin() {
      let account = this.adminInfo.adminAccount;
      let password = md5(this.adminInfo.password);
      this.$api
        .login(account, password)
        .then((res) => {
          console.group("用户登录 =>");
          console.log(res);
          console.groupEnd();
          if (res.code == 0) {
            // 处理 => 响应成功数据
            const userInfo = new this.$api.teacher.AdminUserInfo(
              res.data,
              this.adminInfo.password,
              this.remember
            );
            // 提交给vuex保存用户信息
            this.$store.commit("UPDATE_USER", userInfo);
            // 弹出登录成功
            // this.$message.success("登录成功");
            let hour = new Date().getHours();
            let hourText = "";
            if (hour < 6) {
              hourText = "凌晨好";
            } else if (hour < 9) {
              hourText = "早上好";
            } else if (hour < 12) {
              hourText = "上午好";
            } else if (hour < 14) {
              hourText = "中午好";
            } else if (hour < 17) {
              hourText = "下午好";
            } else if (hour < 19) {
              hourText = "傍晚好";
            } else if (hour < 22) {
              hourText = "晚上好";
            } else {
              hourText = "夜里好";
            }
            this.$notify({
              title: `${hourText} ${account}`,
              message: "欢迎登录英语口语模拟训练系统",
              type: "success",
              offset: 60,
              duration: 1500,
            });
            // 跳转身份对应首页
            // this.$router.push(this.jumpRouterName);
          } else {
            this.$message.error(res.message);
          }
          // this.logining = false;
        })
        .catch((err) => {
          console.log("[异常] 用户登录 =>", err);
          this.$message.error("请求异常，请重试");
        })
        .finally(() => {
          // 无论错误与正确都会进入的函数
          this.logining = false;
        });
    },

    // ======================= 前端功能 =======================
    // 回车事件「登录」
    EnterConfirm(event) {
      // console.log("okoko =>", event);
      if (
        event.code == "Enter" ||
        event.code == "NumpadEnter" ||
        event.key == "Enter"
      ) {
        this.onUserLogin();
      }
    },

    // ======================= 前端事件 =======================
    // 点击登录按钮
    onUserLogin() {
      this.$refs.adminRuleForm.validate((valid) => {
        if (valid) {
          // 验证通过
          this.logining = true;
          this.TheLogin();
        } else {
          // 未通过
          this.$message.error("账号或密码不能为空");
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  background-image: url();
  // background-color: #112346;
  background-color: @bg-color;
  background-repeat: no-repeat;
  background-position: center right;
  background-size: 100%;
  // 「1」 登录框包裹层
  .login-wrap {
    margin-top: 18vh;
    width: 500px;
    // 「2」 登录框 标题部分
    .login-title {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: center;
      text-align: center;
      // LOGO
      .img {
        width: 55px;
        height: 55px;
        line-height: 55px;
        color: #000;
        background: #fff;
      }
      // 标题
      .title-text {
        margin-left: 15px;
        font-size: @title;
        font-weight: bold;
      }
      // 标题描述
      .title-desc {
        margin-top: 20px;
        margin-bottom: 35px;
        width: 100%;
        color: @gray4-color;
        font-size: @t5;
        font-weight: normal;
      }
    }
    // 「2」 登录框 输入框内容部分
    .login-container {
      display: flex;
      // 内部登录块
      .login-internal {
        width: 80%;
        margin: 25px auto 0;
        // 根据项目UI的表单样式
        .login-form {
          margin-top: 35px;
          // 前缀icon公共样式
          .login-icon {
            width: 24px;
            height: 24px;
            // margin-left: 10px;
            margin-top: 8px;
            background: url() no-repeat center;
            background-size: 100% 100%;
          }
          // 管理账号icon
          .login-icon-manage {
            background-image: url(/static/icon-manage.png);
          }
          // 密码icon
          .login-icon-password {
            background-image: url(/static/icon-password.png);
          }
          // 记住密码
          .remember {
            margin-bottom: 30px;
          }
          // 登录按钮
          .login-btn {
            display: flex;
            width: 100%;
            height: 45px;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            font-weight: normal;
            letter-spacing: 8px;
            background: @blue-color;
          }
        }
      }
    }
  }
}
</style>

<style lang="less" scoped>
/deep/ .el-input__inner {
  // 设置半透明
  background: rgba(255, 255, 255, 0.5);
}
// TODO: 这里面的样式是针对本次项目原型进行开发的，如有其它需求自己改下
.login-tabs {
  margin: 0 20px;
  height: 35px;
  // height: 40px;
  position: relative;
  display: flex;
  justify-content: space-between;
  // 给元素添加动画
  .tabs-animate {
    transition: all 0.3s linear;
  }
  // 选项卡元素
  .tabs-item {
    flex: 1;
    text-align: center;
    cursor: pointer;
    user-select: none;
    font-size: 18px;
  }
  // 选项激活后的样式
  .tabs-active {
    color: @blue-color;
  }
  // 底部蓝条
  .tabs-border {
    width: 40%;
    position: absolute;
    bottom: 0;
    height: 3px;
    border-radius: 2px;
    background: @blue-light-color;
    // TODO: 居中对齐 只有一个选项卡时才如此设置的
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>